<template>
  <div class="home">
    <el-row style="width: 80%;margin: auto;">
      <el-col :span="3">

        <div>
          <p style="color: #409EFF;">总浏览量：{{visitsTotal}}</p>
          <p style="color: orange;">独立访问IP：{{visitsIPNum}}</p>
        </div>
      </el-col>
      <el-col :span="21">

        <div id="chart_example2">

        </div>
      </el-col>
    </el-row>


    <h2 class="title">
      按照标签和日期查看访问链曲线
    </h2>
    <el-row style="width: 80%;margin: 10px auto;">
      <el-col :span="6">

        <span class="el-row-col_span">标签:</span>
        <el-tooltip content="标签">
          <el-select v-model="params.labelName" filterable clearable allow-create default-first-option multiple
            placeholder="请选择标签" size="small">
            <el-option v-for="(item) in liveLabelList" :label="item.labelName" :value="item.labelName">
            </el-option>
          </el-select>
        </el-tooltip>
      </el-col>
      <el-col :span="12">

        <span class="el-row-col_span">访问时间:</span>
        <el-tooltip content="创建时间">
          <el-date-picker v-model="params.visitTime" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" size="small">
          </el-date-picker>
        </el-tooltip>
      </el-col>
      <el-col :span="6">
        <span class="seach-btn">
          <el-button class="base-btn" icon="el-icon-search" type="primary" @click="getVisitDay(true)">查询
          </el-button>
        </span>
      </el-col>
      <el-col></el-col>
      <el-col>

        <div id="chart_example">

        </div>
      </el-col>

    </el-row>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        visitsTotal: 0,
        visitsIPNum: 0,

        dataList: [],
        params: {
          labelName: ['区块链', '科技', '二次元'],
          visitTime: [new Date() - 3600 * 1000 * 24 * 7, new Date()]
        },
        liveLabelList: []
      }
    },
    mounted() {
      this.getVisitsTotal();
      this.getVisitDayLabel();
      this.getVisitDay();
      this.initLiveLabelList();
    },
    methods: {
      async initLiveLabelList() {
      let res = await this.$axios.post(this.API.list.getLiveLabel);
      if (res.data.code == "0") {
        this.liveLabelList = res.data.data
      }

        // this.$axios.get('/api/projectApi/getLiveLabel').then((res) => {
        //   if (res.data.code == "0") {
        //     this.liveLabelList = res.data.data
        //   }
        // }, (err) => {
        // }).then(() => {

        // }, (err) => {
        // })

      },

      //总访问量
      async getVisitsTotal() {


      let res = await this.$axios.post(this.API.list.getVisitsTotal);
      if (res.data.code == "0") {
        this.visitsTotal = res.data.data[0][0].visitTotal;
        this.visitsIPNum = res.data.data[1][0].ipNum;
      }

        // this.$axios.post('/api/projectApi/getVisitsTotal', {}).then((res) => {
        //   this.visitsTotal = res.data.data[0][0].visitTotal;
        //   this.visitsIPNum = res.data.data[1][0].ipNum;

        // });

      },
      //日访问量
      async getVisitDay() {

        let parmas = {};

        //创建时间
        if (this.params.visitTime && this.params.visitTime.length > 0) {
          this.params.startDate = this.$options.filters['formatDate'](this.params.visitTime[0])
          this.params.endDate = this.$options.filters['formatDate'](this.params.visitTime[1])
        }
        document.getElementById('chart_example').innerHTML = "";
        document.getElementById("chart_example").removeAttribute("_echarts_instance_");
        var dataList = []

      let res = await this.$axios.post(this.API.list.getVisitsDay, this.params);
      if (res.data.code == "0") {
        dataList = res.data.data;

          //获取选择日期跨度之间的所有日期
          var days = this.$options.filters['getAllDate'](this.params.startDate, this.params.endDate)

          let arr = [];
          var series = [];
          for (var i in dataList) {
            arr.push(dataList[i].labelName)

            var seriesData = [];
            var arrDate = []

            //将日期添加到数组中
            for (var j in dataList[i].data) {
              arrDate.push(dataList[i].data[j].date)
            }

            //获取不存在的日期并添加到dataList中，默认num为0
            var arrDate2 = this.$options.filters['getArrDifference'](arrDate, days);
            for (var a in arrDate2) {
              dataList[i].data.push({ date: arrDate2[a], num: 0 })
            }

            //按日期排序
            dataList[i].data.sort(function (a, b) {
              return Date.parse(a.date.replace(/-/g, "/")) - Date.parse(b.date.replace(/-/g, "/"));
            })

            for (var j in dataList[i].data) {
              seriesData.push(dataList[i].data[j].num)
            }

            series.push({
              name: dataList[i].labelName,
              type: 'line',
              data: seriesData
            })
          }
          console.log(series)
          this.chart_example("chart_example", arr, days, series)

      }

        // this.$axios.post('/api/projectApi/getVisitsDay', this.params).then((res) => {
          
        // });
      },
      //获取今日标签访问量
      async getVisitDayLabel() {

        let res = await this.$axios.post(this.API.list.getVisitDayLabel);
      if (res.data.code == "0") {
        let dataList = res.data.data;
          let seriesData = [];

          let arr = [];
          for (let i = 0; i < dataList.length; i++) {
            arr.push(dataList[i].labelName)

            seriesData.push({
              value: dataList[i].visitNum, name: dataList[i].labelName,
              label: {
                formatter: '{b} : {c} ({d}%)'
              },
            })
          }
          let myChart = this.$echarts.init(document.getElementById("chart_example2"));
          let option = {
            title: {
              text: '今日板块访问量',
              // subtext: '纯属虚构',
              left: 'center'
            },
            tooltip: {
              trigger: 'item',
              formatter: '{a} <br/>{b} : {c} ({d}%)'
            },
            legend: {
              orient: 'vertical',
              bottom: 'bottom',
              data: arr
            },
            series: [
              {
                name: '访问来源',
                type: 'pie',
                radius: '55%',
                center: ['50%', '60%'],
                data: seriesData,
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                }
              }
            ]
          };
          myChart.setOption(option);
          window.addEventListener('resize', function () { myChart.resize() });
      }
        // this.$axios.post('/api/projectApi/getVisitDayLabel', {}).then((res) => {
          

        // });
      },

      //绘图
      chart_example(chart_example, legendData, days, series) {

        var series2 = [];
        var days2 = [];
        var legendData2 = []

        series2 = series
        days2 = days
        legendData2 = legendData

        let myChart = this.$echarts.init(document.getElementById(chart_example));
        let option = {
          title: {
            text: '日访问量'
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            type: 'scroll',
            orient: 'vertical',
            right: 0,
            top: 20,
            bottom: 20,
            data: legendData2
          },
          toolbox: {
            feature: {
              saveAsImage: {}
            }
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            splitLine: { show: false },
            data: days2
          },
          yAxis: {
            type: 'value',
            minorTick: {
              show: true
            },
            minorSplitLine: {
              show: true
            }
          },
          series: series2
        };
        myChart.setOption(option);

        window.addEventListener('resize', function () { myChart.resize() });
      },
      // 计算续住的总日期列表

    },
    watch: {},
    created() {

    }
  }
</script>

<style scoped>
  h2 {
    text-align: center;
    padding: 30px;
    font-size: 18px;
    border-top: 1px solid #efefef;
  }

  #chart_example {
    width: 100%;
    height: 500px;
    /* border: 1px solid red; */
    margin: 0 auto;
  }

  #chart_example2 {
    width: 100%;
    height: 300px;
    margin: 0 auto;
    padding: 10px;
  }

  .el-row {
    padding: 10px 0;
  }
</style>